<template>
  <div class="app-container">
    <el-form
      :inline="true"
      :model="keyword"
      ref="searchForm"
      class="demo-form-inline"
    >
      <el-form-item label="桌码">
        <el-input
          size="small"
          clearable
          v-model="keyword.deskCode"
          placeholder="桌码"
        ></el-input>
      </el-form-item>
      <el-form-item label="餐桌状态">
        <el-select v-model="keyword.status" placeholder="餐桌状态">
          <el-option
            v-for="status in statuses"
            :key="status.id"
            :label="status.status"
            :value="status.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-button type="primary" @click="searchEmp()">搜索</el-button>
      <el-button
        type="primary"
        @click="resetSearchForm()"
        icon="el-icon-refresh"
      >
        重置
      </el-button>
      <el-button type="primary" @click="handleAdd()">新增</el-button>
      <el-button type="primary" @click="deleteBatch()">批量删除</el-button>
    </el-form>

    <el-table
      :data="employeeList"
      v-loading="listLoading"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      stripe
      style="width: 100%; margin-top: 10px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column prop="id" label="id" width="140">
      </el-table-column>
      <el-table-column
        prop="deskCode"
        label="桌码"
        width="160"
      ></el-table-column>
      <el-table-column
        prop="seatNum"
        label="人数限制"
        width="160"
      ></el-table-column>
      <el-table-column
        prop="shopName"
        label="所属店铺"
        width="180"
      ></el-table-column>
      <el-table-column
        prop="createDate"
        label="创建时间"
        width="200"
      ></el-table-column>
      <el-table-column
        prop="status"
        label="状态"
        width="120">
        <template slot-scope="scope">
          <el-tag
            v-if="scope.row.status == 1"
            :type="scope.row.status == 1 ? 'success' : 'info'"
            disable-transitions
          >启用</el-tag
          >
          <el-tag
            v-if="scope.row.status != 1"
            :type="scope.row.status == 1 ? 'success' : 'info'"
            disable-transitions
          >禁用</el-tag
          >
        </template>
        <el-switch
          v-model="value"
          active-color="#13ce66"
          inactive-color="#ff4949">
        </el-switch>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="showQRcode(scope.row)"
          >二维码</el-button
          >
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
          >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
          >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 10px"
    >
    </el-pagination>

    <!-- 添加对话框 -->
    <el-dialog title="新增餐桌" :visible.sync="dialogFormVisible">
      <el-form :model="addFrom">
        <el-form-item label="桌码" :label-width="formLabelWidth">
          <el-input v-model="addFrom.deskCode" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="人数限制" :label-width="formLabelWidth">
          <el-input-number v-model="addFrom.seatNum" @change="handleChange" :min="1" :max="10"></el-input-number>
        </el-form-item>
        <el-form-item label="所属店铺" :label-width="formLabelWidth">
          <el-select v-model="addFrom.belongingStoreId" placeholder="请选择">
            <el-option
              v-for="shop in shops"
              :key="shop.belongingStoreId"
              :label="shop.name"
              :value="shop.belongingStoreId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="餐桌状态" :label-width="formLabelWidth">
          <el-select v-model="addFrom.status" placeholder="请选择">
            <el-option
              v-for="status in statuses"
              :key="status.id"
              :label="status.status"
              :value="status.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="上传二维码" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/shop/desk/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="add()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog title="修改餐桌" :visible.sync="dialogUpdateFormVisible">
      <el-form :model="updateFrom">
        <el-form-item label="桌码" :label-width="formLabelWidth">
          <el-input v-model="updateFrom.deskCode" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="人数限制" :label-width="formLabelWidth">
          <el-input-number v-model="updateFrom.seatNum" @change="handleChange" :min="1" :max="10"></el-input-number>
        </el-form-item>
        <el-form-item label="所属店铺" :label-width="formLabelWidth">
          <el-select v-model="updateFrom.belongingStoreId" placeholder="请选择">
            <el-option
              v-for="shop in shops"
              :key="shop.belongingStoreId"
              :label="shop.name"
              :value="shop.belongingStoreId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="餐桌状态" :label-width="formLabelWidth">
          <el-select v-model="updateFrom.status" placeholder="请选择">
            <el-option
              v-for="status in statuses"
              :key="status.id"
              :label="status.status"
              :value="status.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogUpdateFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="update()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog title="二维码" :visible.sync="dialogQRcodeFormVisible">
      <el-image :src="qrCode" style="width: 300px; height: 300px"></el-image>
    </el-dialog>
  </div>
</template>

<script>
import { getShops } from "@/api/shopList";
import {deskPage, delDesk, delBatchDesk, addDesk, deskInfo, updateDesk} from "@/api/desk"
import { empType } from "@/api/empType"
export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger",
      };
      return statusMap[status];
    },
  },
  data() {
    return {
      value1: true,
      value2: false,
      employeeList: [],
      listLoading: true,
      dialogFormVisible: false,
      dialogUpdateFormVisible: false,
      dialogQRcodeFormVisible: false,
      qrCode: '',
      keyword: {
        deskCode: "",
        status: "",
      },
      addFrom: {
        deskCode: "",
        seatNum: "",
        shopName: "",
        status: "",
        qrCode: "",
      },
      updateFrom: {
        id: "",
        deskCode: "",
        seatNum: "",
        belongingStoreId: "",
        status: "",
      },
      formLabelWidth: "120px",
      currentPage: 1,
      total: 0,
      pageSize: 5,
      ids: [],
      empTypes: [],
      shops: [],
      imageUrl: '',
      statuses: [
        {
          id: 1,
          status: "启用",
        },
        {
          id: 2,
          status: "禁用",
        },
      ],
    };
  },
  created() {
    this.fetchData();
    this.searchEmpType();
    this.searchShop();
  },
  methods: {
    showQRcode(row){
      deskInfo(row.id).then((res) => {
        console.log(res.data.qrCode)
        this.qrCode = res.data.qrCode
      });
      this.dialogQRcodeFormVisible = true
    },
    handleChange(val){
      console.log(val)
    },
    searchEmpType(){
      empType().then(res => {
        this.empTypes = res.data
      })
    },
    searchShop(){
      getShops().then(res => {
        this.shops = res.data
      })
    },
    fetchData() {
      this.listLoading = false;
      deskPage({
        deskCode: this.keyword.deskCode,
        status: this.keyword.status,
        pageNum: this.currentPage,
        pageSize: this.pageSize,
      }).then((response) => {
        console.log(response)
        this.employeeList = response.data.list;
        this.total = response.data.total;
        this.listLoading = false;
      });
    },
    searchEmp() {
      this.fetchData();
    },
    handleAdd() {
      this.addFrom = {};
      this.dialogFormVisible = true;
    },
    // 添加
    add() {
      console.log(this.addFrom)
      addDesk(this.addFrom).then((response) => {
        if (response.code == 200) {
          this.dialogFormVisible = false;
          this.fetchData();
        }else {
          this.$message({
            message: response.msg,
            type: "error",
            duration: 1000
          })
        }
      });
    },
    // 修改
    handleEdit(index, row) {
      deskInfo(row.id).then((res) => {
        this.updateFrom.id = res.data.id
        this.updateFrom.deskCode = res.data.deskCode
        this.updateFrom.seatNum = res.data.seatNum
        this.updateFrom.belongingStoreId = res.data.belongingStoreId
        this.updateFrom.status = res.data.status
      });
      this.dialogUpdateFormVisible = true;
    },
    update() {
      updateDesk(this.updateFrom).then((response) => {
        if (response.code == 200) {
          this.dialogUpdateFormVisible = false;
          this.fetchData();
        }
      });
    },
    handleDelete(index, row) {
      this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delDesk(row.id).then((response) => {
            if (response.code == 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.fetchData();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 每页显示的记录数发生变化触发的操作
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.fetchData();
    },
    // 当前页发生变化触发的操作
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.fetchData();
    },
    handleSelectionChange(val) {
      this.ids = [];
      for (var i = 0; i < val.length; i++) {
        this.ids.push(val[i].id);
      }
    },
    deleteBatch() {
      // 提示，自行处理
      if (this.ids.length == 0) {
        alert("请选择至少一条数据");
        return;
      }
      delBatchDesk(this.ids.join(",")).then((response) => {
        if (response.code == 200) {
          this.$message({
            message: "批量删除成功",
            type: "success",
            duration: 1000,
          });
          this.fetchData();
        } else {
          this.$message({
            message: "批量删除失败",
            type: "error",
            duration: 1000,
          });
        }
      });
    },
    handleAvatarSuccess(res, file) {
      console.log(res)
      this.addFrom.qrCode = res.data
      console.log(this.addFrom)
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    resetSearchForm() {
      this.keyword = {};
      this.fetchData();
    },
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
